package com.bocai.dahuatech.ui.frag;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bocai.dahuatech.Bean.BaseBean;
import com.bocai.dahuatech.Bean.IndividualBean;
import com.bocai.dahuatech.Bean.ShopCardListBean;
import com.bocai.dahuatech.Bean.ShopcardTotalPriceBean;
import com.bocai.dahuatech.R;
import com.bocai.dahuatech.base.BaseFragment;
import com.bocai.dahuatech.event.MainEvent;
import com.bocai.dahuatech.ui.activity.ConfirmOrderActivity;
import com.bocai.dahuatech.ui.activity.RegistDistributorSecendActivity;
import com.bocai.dahuatech.ui.adapter.MyShoppingcardAdapter;
import com.bocai.dahuatech.utils.AESUtils;
import com.bocai.dahuatech.utils.DialogUtil;
import com.bocai.dahuatech.utils.SharePrefencesUtil;
import com.google.gson.Gson;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * 购物车主界面
 */
public class Fragment_ShoppingCart extends BaseFragment implements View.OnClickListener{
    private View view;
    @Bind(R.id.swipe_shopcard)
    SwipeRefreshLayout swipeShopcard;
    @Bind(R.id.title_tv)
    TextView tvTitle;
    @Bind(R.id.tv_settlement)
    TextView tvSettlement;
    @Bind(R.id.lv_shoppingcard)
    ListView lvShoppingCard;
    @Bind(R.id.cb_shoppingcard_selectall)
    CheckBox cbSelectAll;
    @Bind(R.id.ll_bottom)
    LinearLayout llBottom;
    @Bind(R.id.tv_shoppingcard_totalprice)
    TextView tvTotalPrice;
    MyShoppingcardAdapter adapter;
    ShopCardListBean shopCardListBean=new ShopCardListBean();
    int totalCount=0;
    String  totalPrice;
    int clickposition;
    int clickCount;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
    {
        view = inflater.inflate(R.layout.shoppingcardfrag, container, false);
        initView(view);
        return view;
    }

    @Override
    public void onResume()
    {
        super.onResume();
        getDatas();


    }
    private void initView(View view)
    {
        ButterKnife.bind(this, view);
        tvTitle.setText("购物车");
        initEvent();
    }

    int deleteCount;

    @Override
    public void onEventMainThread(MainEvent event)
    {
        super.onEventMainThread(event);
        if(event.msg.equals(getResources().getString(R.string.settlement)))
        {
            clickposition=event.position;
            clickCount=event.fQty;
            if(event.fStatus==1)//单个产品选中
            {
                getAfterCartInfoEdit(event.fEntryID, event.fQty, event.fStatus);
                totalCount=totalCount+1;
//            totalPrice=totalPrice+shopCardListBean.getContent().get(event.position).getFStandPrice()*event.fQty;
//            setTotal();
            }else if(event.fStatus==0)//单个产品取消选中
            {
                getAfterCartInfoEdit(event.fEntryID, event.fQty, event.fStatus);
                totalCount=totalCount-1;
//            totalPrice=totalPrice-shopCardListBean.getContent().get(event.position).getFStandPrice()*event.fQty;
//            setTotal();
            }else if(event.fStatus==2) //单个产品数量减少
            {
                getAfterCartInfoEdit(event.fEntryID, event.fQty, 1);
//            totalCount=totalCount-1;
//            totalPrice=totalPrice-shopCardListBean.getContent().get(event.position).getFStandPrice();
//            setTotal();
            }else if(event.fStatus==3)//单个产品数量增加
            {
                getAfterCartInfoEdit(event.fEntryID, event.fQty, 1);
//            totalCount=totalCount-1;
//            totalPrice=totalPrice+shopCardListBean.getContent().get(event.position).getFStandPrice();
//            setTotal();
            }
            else if(event.fStatus==4)//数量编辑
            {
                getAfterCartInfoEdit(event.fEntryID, event.fQty, 1);
//            totalCount=totalCount-1;
//            totalPrice=totalPrice+shopCardListBean.getContent().get(event.position).getFStandPrice()*event.addnum;
//            setTotal();
            }
            else if(event.fStatus==5)//删除
            {
                deleteCount=event.fQty;
                longClickPosition=event.position;
                getAfterCartInfoEdit(event.fEntryID, event.fQty, 2);
//            totalCount=totalCount-1;
//            totalPrice=totalPrice+shopCardListBean.getContent().get(event.position).getFStandPrice()*event.addnum;
//            setTotal();
            }
        }

    }

    private void setTotal()
    {
        if(SharePrefencesUtil.getFAccessFlag(getActivity())==2)
        {

            tvTotalPrice.setText(getResources().getString(R.string.moneytotal)+totalPrice);

        }
        //去结算(2)
        tvSettlement.setText(getResources().getText(R.string.tosettlement)+"(" + totalCount + ")");
    }

    /**
     * 获取购物车列表
     */
    private void getDatas()
    {
        totalCount=0;
        getTestApi().getShopcardList(SharePrefencesUtil.getFID(getActivity())+"")
                .compose(this.<BaseBean>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }
    Observer<BaseBean> observer=new Observer<BaseBean>()
    {
        @Override
        public void onCompleted()
        {
            for (int i = 0; i < shopCardListBean.getContent().size(); i++)
            {
                if(shopCardListBean.getContent().get(i).getFStatus()==1)
                {
                    if(!shopCardListBean.getContent().get(i).isFFitting())
                    {
                        totalCount=totalCount+1;
                    }
//                    totalPrice=totalPrice+(shopCardListBean.getContent().get(i).getFStandPrice()*shopCardListBean.getContent().get(i).getFBQty());
                }
            }
            setTotal();
        }
        @Override
        public void onError(Throwable e)
        {
            hideLoading();
            swipeShopcard.setRefreshing(false);
            showToast(R.string.neterror);
            Log.e("error",e.toString());
        }

        @Override
        public void onNext(BaseBean baseBean)
        {
            hideLoading();
            swipeShopcard.setRefreshing(false);
            if(baseBean.getReturnNo().equals("1"))
            {
                llBottom.setVisibility(View.VISIBLE);
                ShopcardTotalPriceBean priceBean=new Gson().fromJson(baseBean.getReturnInfo(),ShopcardTotalPriceBean.class);
                String result= AESUtils.decode(baseBean.getContent());
                result=start+result+end;
                Log.e("result",result);
                shopCardListBean=new Gson().fromJson(result,ShopCardListBean.class);
                adapter=new MyShoppingcardAdapter(getActivity(),shopCardListBean.getContent());
                lvShoppingCard.setAdapter(adapter);
                totalPrice=priceBean.getTotalAmount();

            }else
            {
                Log.e("result",baseBean.getReturnInfo());
                llBottom.setVisibility(View.GONE);
            }
        }
    };
    int longClickPosition;
    private void initEvent()
    {
        tvSettlement.setOnClickListener(this);
        cbSelectAll.setOnClickListener(this);
        swipeShopcard.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getDatas();
            }
        });
    }

    @Override
    public void onDestroyView()
    {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }



    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.tv_settlement:
                //如果用户没有勾选任何产品，则不会跳转，提醒用户您还未勾选任何产品
                if(SharePrefencesUtil.getFAccessFlag(getActivity())==2)
                {

                    boolean ifSelect=false;
                    for (int i=0;i<adapter.selectedMap.size();i++)
                    {
                        if (adapter.selectedMap.get(i))
                        {
                            ifSelect=true;
                        }
                    }
                    if(ifSelect)
                    {
                        Intent intent= new Intent(getActivity(), ConfirmOrderActivity.class);
                        intent.putExtra("totalprice",tvTotalPrice.getText().toString());
                        startActivity(intent);
                    }else
                    {
                        DialogUtil.dialogForOneButton(getActivity(),R.string.notchooseproduct,R.string.know);
                    }
                }else{
                    DialogUtil.dialogForTwoButton(getActivity(), R.string.onlydistributorcanconfirmorder, R.string.know, R.string.toauthentication, new View.OnClickListener()
                    {
                        @Override
                        public void onClick(View v)
                        {
                            if (SharePrefencesUtil.getFAccessFlag(getActivity()) == 6)
                            {
                                DialogUtil.dismissTowDialog();
                                DialogUtil.dialogForOneButton(getActivity(), R.string.alreadysubmitdata, R.string.know);
                            } else if (SharePrefencesUtil.getFAccessFlag(getActivity()) == 7)
                            {
                                Intent intent1 = new Intent(getActivity(), RegistDistributorSecendActivity.class);
                                IndividualBean bean = new IndividualBean();
                                intent1.putExtra("register", bean);
                                intent1.putExtra("what", "certifiled");
                                startActivity(intent1);
                            }
                        }
                    });
                }
                break;
            case R.id.cb_shoppingcard_selectall:
                // 全选CheckBox的click事件处理
                if (cbSelectAll.isChecked()) //全部选中
                {
                    for (int i = 0; i < adapter.getCount(); i++)
                    {
                        adapter.selectedMap.put(i, true);

                    }
                    totalCount=0;
                    for (int i = 0; i < shopCardListBean.getContent().size(); i++)
                    {
                        if(shopCardListBean.getContent().get(i).getFStatus()==1)
                        {
                            totalCount=totalCount+1;
//                            totalPrice=totalPrice+(shopCardListBean.getContent().get(i).getFStandPrice()*shopCardListBean.getContent().get(i).getFBQty());
                        }
                    }
                    setTotal();
                    getAfterCartInfoEdit(0,0,1);
                } else   //全部未选中
                {
                    for (int i = 0; i < adapter.getCount(); i++)
                    {
                        adapter.selectedMap.put(i, false);
                    }
                    getAfterCartInfoEdit(0,0,0);
                    totalCount=0;
                    setTotal();
                }
                adapter.notifyDataSetChanged();
                break;
        }
    }

    /**
     * 购物车数量及选中状态修改
     * @param fEntryID
     * @param fQty
     * @param fStatus 0:取消选中；1:选中；2:删除
     */
    private void getAfterCartInfoEdit(int fEntryID,int fQty, final int fStatus)
    {
        getTestApi().getAfterCartInfoEdit(fEntryID, fQty, fStatus, SharePrefencesUtil.getFID(getActivity()),
                SharePrefencesUtil.getCustomerCode(getActivity()),shopCardListBean.getContent().size() )
                .compose(this.<BaseBean>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseBean>()
                {
                    @Override
                    public void onCompleted()
                    {

                    }

                    @Override
                    public void onError(Throwable e)
                    {
                        Log.e("result",e.toString());
                    }

                    @Override
                    public void onNext(BaseBean baseBean)
                    {
                        if(fStatus==0)
                        {
                            if (baseBean.getReturnNo().equals("1"))
                            {
//                                showToast(baseBean.getReturnInfo());
                                totalPrice=baseBean.getReturnInfo();
                                setTotal();
                            }else
                            {
                                showToast(baseBean.getReturnInfo());
                            }
                        }
                        if(fStatus==2)
                        {
                            if (baseBean.getReturnNo().equals("1"))
                            {
                                showToast("删除成功");
                                getDatas();
                            }else
                            {
                                showToast("删除失败");
                            }
                        }
                        if(fStatus==1)
                        {
                            if (baseBean.getReturnNo().equals("1"))
                            {

                                shopCardListBean.getContent().get(clickposition).setFBQty(clickCount);
                                adapter.notifyDataSetChanged();
                                totalPrice=baseBean.getReturnInfo();
                                setTotal();
                            }else
                            {
                                showToast(baseBean.getReturnInfo());
                            }
                        }
                    }
                });
    }
}
